#include "Product.h"
#include "User.h"
#include <fstream>
#include <algorithm> // std::find_if, std::remove_if
#include <limits>    // std::numeric_limits, 清空缓存区用,防止用户输入一大堆没用的

// 清空输入缓冲区
void ProductController::clearInputBuffer() const
{
    std::cin.clear();                                                   // Clear error flags
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Discard characters
}

// --- Product基类方法实现 ---
// 析构函数矫正一下初始化参数
Product::Product(std::string id, std::string name, std::string desc, double price, int qty, std::string cat, int sellerID, double discount, int frozenQty)
    : id(std::move(id)), name(std::move(name)), description(std::move(desc)), originalPrice(price), quantity(qty), category(std::move(cat)), sellerId(sellerID), discountRate(discount), frozenQuantity(frozenQty)
    {
        if (originalPrice < 0)
            originalPrice = 0;
        if (quantity < 0)
            quantity = 0;
        if (discountRate < 0.0 || discountRate > 1.0)
            discountRate = 0.0;
}

std::string Product::getId() const { return id; }
std::string Product::getName() const { return name; }
std::string Product::getDescription() const { return description; }
double Product::getOriginalPrice() const { return originalPrice; }
int Product::getQuantity() const { return quantity; }
std::string Product::getCategory() const { return category; }
double Product::getDiscountRate() const { return discountRate; }
int Product::getSellerId() const { return sellerId; }

void Product::setTotalQuantity(int qty)
{
    if (qty >= 0)
    {
        if (qty < frozenQuantity)
        {
            std::cout << "错误：设置的数量小于冻结的数量。 " << "目前的冻结数量为: " << frozenQuantity << endl;
            return; // 不允许设置小于冻结数量的库存
        }
        quantity = qty;
    }
    else
    {
        std::cout << "错误：数量不能为负。 " << "目前的数量为: " << quantity << endl;
    }
}

void Product::setOriginalPrice(double price)
{
    if (price >= 0)
    {
        originalPrice = price;
    }
    else
    {
        std::cout << "错误：价格不能为负。 " << "目前的价格为: " << originalPrice << endl;
    }
}

void Product::setDiscountRate(double rate)
{
    if (rate >= 0.0 && rate <= 1.0)
    { // rate is 0.0 to 1.0
        discountRate = rate;
    }
    else
    {
        std::cout << "错误：折扣率必须在0.0到1.0之间。 " << "目前的折扣率为: " << discountRate << endl;
    }
}

void Product::setDescription(const std::string &desc)
{
    if (desc.empty())
    {
        description = "该商品无描述~"; // 在amin函数中设置用户选择是否描述，若无描述，传入空串。
    }
    else
    {
        description = desc;
    }
}

void Product::setName(const std::string &newName) { name = newName; }

bool Product::freezeStock(int qty) // 冻结库存,用于订单处理
{
    if (qty > 0 && qty <= getAvailableQuantity())
    {
        frozenQuantity += qty;
        return true;
    }
    else
    {
        std::cout << "错误：订单数量无效。当前可用库存为: " << getAvailableQuantity() << std::endl;
    }
    return false;
}

bool Product::unfreezeStock(int qty) // 取消冻结库存, 如果订单取消
{
    if (qty > 0 && qty <= frozenQuantity)
    {
        frozenQuantity -= qty;
        return true;
    }
    else
    {
        std::cout << "错误：解冻数量无效。当前冻结库存为: " << frozenQuantity << "，尝试解冻的数量为: " << qty << std::endl;
    }
    return false;
}

bool Product::confirmSale(int soldQuantity) // 确认销售,减少总库存和冻结库存(确认销售的操作是将冻结的商品真正的分配出去)
{
    if (soldQuantity > 0 && soldQuantity <= frozenQuantity && soldQuantity <= quantity)
    {
        quantity -= soldQuantity;
        frozenQuantity -= soldQuantity;
        return true;
    }
    return false;
}

double Product::getPrice() const { return originalPrice * (1.0 - discountRate); }

// void Product::displayProductDetails(bool forSeller) const
// {
//     const UserController userCtrl;                            // 创建一个UserController实例，用于获取商家名称
//     std::string sellerName = userCtrl.findUsername(sellerId); // 获取商家名称
//     if (!forSeller)
//     {
//         std::cout << std::fixed << std::setprecision(2);
//         std::cout << "  ID: " << id << "\n";
//         std::cout << "  名称: " << name << "\n";
//         std::cout << "  类型: " << getProductType() << " (分类: " << category << ")\n";
//         std::cout << "  商家: " << sellerName << "\n"; // 显示商家名称
//         std::cout << "  描述: " << description << "\n";
//         if (discountRate > 0.0)
//         {
//             std::cout << "  原价: ¥" << originalPrice << "\n";
//             std::cout << "  折扣: " << (discountRate * 100) << "%\n";
//             std::cout << "  折后价: ¥" << getPrice() << "\n";
//         }
//         else
//         {
//             std::cout << "  价格: ¥" << getPrice() << "\n";
//         }
//         std::cout << "  可购买量: " << getAvailableQuantity() << "\n"; // 显示可用库存量
//         std::cout << "-------------------------------------\n";
//     }
//     else
//     {
//         // 商家视图显示更多信息
//         std::cout << std::fixed << std::setprecision(2);
//         std::cout << "ID: " << id << "\n";
//         std::cout << "  名称: " << name << "\n";
//         std::cout << "  类型: " << getProductType() << " (分类: " << category << ")\n";
//         std::cout << "  描述: " << description << "\n";
//         std::cout << "  原价: ¥" << originalPrice << "\n";
//         if (discountRate > 0.0)
//         {
//             std::cout << "  折扣: " << (discountRate * 100) << "%\n";
//             std::cout << "  折后价: ¥" << getPrice() << "\n";
//         }
//         std::cout << "  剩余量: " << quantity << "\n";
//         std::cout << "  冻结量: " << frozenQuantity << "\n";         // 显示冻结的数量
//         std::cout << "  可用量: " << getAvailableQuantity() << "\n"; // 显示可用库存量
//         std::cout << "-------------------------------------\n";
//     }
// }

nlohmann::json Product::toJson() const // 将商品对象转换为JSON对象并返回
{
    nlohmann::json j;
    j["id"] = id;
    j["name"] = name;
    j["description"] = description;
    j["originalPrice"] = originalPrice;
    j["quantity"] = quantity;
    j["category"] = category;
    j["discountRate"] = discountRate;
    j["sellerId"] = sellerId;             // 新增
    j["frozenQuantity"] = frozenQuantity; // 新增
    return j;
}

// 静态方法：从JSON对象创建Product对象,这个Json对象只是一个object,并不是整个文件
std::unique_ptr<Product> Product::fromJson(const nlohmann::json &j_product)
{
    try
    {
        std::string id = j_product["id"].get<std::string>();
        std::string name = j_product["name"].get<std::string>();
        std::string description = j_product["description"].get<std::string>();
        double originalPrice = j_product["originalPrice"].get<double>();
        int quantity = j_product["quantity"].get<int>();
        std::string category_str = j_product["category"].get<std::string>();
        double discountRate = j_product.value("discountRate", 0.0); // Default to 0.0 if not present
        int seller_id = j_product.value("sellerId", 0);             // 假设默认超级sellerId为0
        int frozen_qty = j_product.value("frozenQuantity", 0);

        if (category_str == "Book")
        {
            return std::make_unique<BookProduct>(id, name, description, originalPrice, quantity, frozen_qty, seller_id, discountRate);
        }
        else if (category_str == "Clothing")
        {
            return std::make_unique<ClothingProduct>(id, name, description, originalPrice, quantity, frozen_qty, seller_id, discountRate);
        }
        else if (category_str == "Food")
        {
            return std::make_unique<FoodProduct>(id, name, description, originalPrice, quantity, frozen_qty, seller_id, discountRate);
        }
        else
        {
            std::cerr << "错误：未知的商品分类 '" << category_str << "' 在JSON数据中。\n";
            return nullptr;
        }
    }
    catch (const nlohmann::json::exception &e)
    {
        std::cerr << "从JSON解析商品时出错: " << e.what() << std::endl;
        return nullptr;
    }
}

// --- Book派生类方法实现 ---
BookProduct::BookProduct(std::string id, std::string name, std::string desc, double price, int qty, int frozenQty, int sellerID, double discount)
    : Product(std::move(id), std::move(name), std::move(desc), price, qty, "Book", sellerID, discount, frozenQty) {}

std::string BookProduct::getProductType() const
{
    return "Book";
}

// --- Clothing派生类方法实现 ---
ClothingProduct::ClothingProduct(std::string id, std::string name, std::string desc, double price, int qty, int frozenQty, int sellerID, double discount)
    : Product(std::move(id), std::move(name), std::move(desc), price, qty, "Clothing", sellerID, discount, frozenQty) {}

std::string ClothingProduct::getProductType() const
{
    return "Clothing";
}

// --- Food派生类方法实现 ---
FoodProduct::FoodProduct(std::string id, std::string name, std::string desc, double price, int qty, int frozenQty, int sellerID, double discount)
    : Product(std::move(id), std::move(name), std::move(desc), price, qty, "Food", sellerID, discount, frozenQty) {}

std::string FoodProduct::getProductType() const
{
    return "Food";
}

// --- ProductController实现方法---
ProductController::ProductController(const std::string &filePath) : productFilePath(filePath)
{
    loadProducts();
}

ProductController::~ProductController()
{
    saveProducts();
}

std::string ProductController::generateNewProductId() const
{
    if (products.empty())
    {
        return "P001";
    }
    int maxIdNum = 0;
    for (const auto &p_ptr : products)
    {
        if (p_ptr->getId().rfind("P", 0) == 0 && p_ptr->getId().length() > 1)
        { // ID是以"P"开头的string
            try
            {
                int currentIdNum = std::stoi(p_ptr->getId().substr(1));
                if (currentIdNum > maxIdNum)
                {
                    maxIdNum = currentIdNum;
                }
            }
            catch (const std::invalid_argument &ia)
            {
                cerr << "无效的商品ID格式: " << p_ptr->getId() << ". 应该是以 'P' 开头后跟数字。\n";
            }
            catch (const std::out_of_range &oor)
            {
                cerr << "商品ID数字超出范围: " << p_ptr->getId() << ". 请检查商品ID格式。\n";
            }
        }
    }
    std::ostringstream oss;
    oss << "P" << std::setw(3) << std::setfill('0') << (maxIdNum + 1);
    return oss.str();
}

void ProductController::loadProducts()
{
    products.clear(); // Clear existing products before loading

    nlohmann::json j_array = JsonHandler::loadFormFile(productFilePath);

    for (const auto &j_product : j_array)
    {
        auto product_ptr = Product::fromJson(j_product);
        if (product_ptr)
        {
            products.push_back(std::move(product_ptr));
        }
    }
}

void ProductController::saveProducts() const
{
    nlohmann::json j_array = nlohmann::json::array();
    for (const auto &product_ptr : products)
    {
        if (product_ptr)
        {
            j_array.push_back(product_ptr->toJson());
        }
    }
    try
    {
        JsonHandler::saveToFile(productFilePath, j_array);
    }
    catch (const std::runtime_error &e)
    {
        std::cerr << "保存商品到文件失败 (" << productFilePath << "): " << e.what() << std::endl;
    }
}

bool ProductController::addProduct(std::unique_ptr<Product> product)
{
    if (!product)
        return false;
    auto it = std::find_if(products.begin(), products.end(),
                            [&](const std::unique_ptr<Product> &p)
                            { return p->getId() == product->getId(); });
    if (it != products.end())
    {
        std::cout << "错误：商品ID '" << product->getId() << "' 已存在。\n";
        return false;
    }
    products.push_back(std::move(product));
    saveProducts(); // Save after each addition
    return true;
}

// bool ProductController::addProductInteractively(const User &currentUser)
// {
//     if (currentUser.getUsertype() != "Seller")
//     {
//         std::cout << "只有商家才能添加商品。\n";
//         return false;
//     }

//     std::cout << "--- 添加新商品 ---\n";
//     std::string name, description, category_choice_str;
//     double price;
//     int quantity_val;
//     int category_choice;

//     std::cout << "请选择商品分类:\n";
//     std::cout << "1. 图书 (Book)\n";
//     std::cout << "2. 服装 (Clothing)\n";
//     std::cout << "3. 食品 (Food)\n";
//     std::cout << "请输入选项: ";

//     while (!(std::cin >> category_choice) || category_choice < 1 || category_choice > 3)
//     {
//         std::cout << "无效的选项，请输入1, 2, 或 3: ";
//         clearInputBuffer();
//     }
//     clearInputBuffer(); // Consume newline after number input

//     std::string category_str;
//     std::unique_ptr<Product> newProduct = nullptr;
//     std::string newId = generateNewProductId();

//     std::cout << "请输入商品名称: ";
//     std::getline(std::cin, name);

//     std::cout << "请输入商品描述: ";
//     std::getline(std::cin, description);

//     std::cout << "请输入商品原价: ";
//     while (!(std::cin >> price) || price < 0)
//     {
//         std::cout << "无效的价格，请输入一个非负数: ";
//         clearInputBuffer();
//     }
//     clearInputBuffer();

//     std::cout << "请输入商品数量: ";
//     while (!(std::cin >> quantity_val) || quantity_val < 0)
//     {
//         std::cout << "无效的数量，请输入一个非负整数: ";
//         clearInputBuffer();
//     }
//     clearInputBuffer();

//     switch (category_choice)
//     {
//     case 1:
//         newProduct = std::make_unique<BookProduct>(newId, name, description, price, quantity_val, 0, currentUser.getId(), 0.0);
//         break;
//     case 2:
//         newProduct = std::make_unique<ClothingProduct>(newId, name, description, price, quantity_val, 0, currentUser.getId(), 0.0);
//         break;
//     case 3:
//         newProduct = std::make_unique<FoodProduct>(newId, name, description, price, quantity_val, 0, currentUser.getId(), 0.0);
//         break;
//     default: // Should not happen due to previous validation
//         std::cout << "内部错误：无效的分类选择。\n";
//         return false;
//     }

//     if (addProduct(std::move(newProduct)))
//     {
//         std::cout << "商品 '" << name << "' (ID: " << newId << ") 添加成功！\n";
//         return true;
//     }
//     else
//     {
//         std::cout << "商品添加失败。\n";
//         return false;
//     }
// }



void ProductController::displayProductsByCategory(const std::string &category) const
{
    bool found = false;
    std::cout << "\n--- 分类商品: " << category << " ---\n";
    for (const auto &product_ptr : products)
    {
        if (product_ptr && product_ptr->getCategory() == category)
        {
            //product_ptr->displayProductDetails();
            found = true;
        }
    }
    if (!found)
    {
        std::cout << "未找到分类为 '" << category << "' 的商品。\n";
    }
}

std::vector<Product *> ProductController::searchProductByName(const std::string &nameQuery) const
{
    vector<Product *> results;
    bool found = false;
    std::string lowerNameQuery = nameQuery;
    std::transform(lowerNameQuery.begin(), lowerNameQuery.end(), lowerNameQuery.begin(), ::tolower);

    std::cout << "\n--- 名称包含 '" << nameQuery << "' 的搜索结果 ---\n";
    for (const auto &product_ptr : products)
    {
        if (product_ptr)
        {
            std::string lowerProductName = product_ptr->getName();
            std::transform(lowerProductName.begin(), lowerProductName.end(), lowerProductName.begin(), ::tolower);
            if (lowerProductName.find(lowerNameQuery) != std::string::npos)
            {
                results.push_back(product_ptr.get());
                found = true;
            }
        }
    }
    if (!found)
    {
        std::cout << "未找到名称包含 '" << nameQuery << "' 的商品。\n";
    }
    return results;
}

Product *ProductController::findProductById(const std::string &productId)
{
    auto it = std::find_if(products.begin(), products.end(),
                            [&](const std::unique_ptr<Product> &p)
                            { return p && p->getId() == productId; });
    if (it != products.end())
    {
        return it->get(); // 返回原始指针
    }
    return nullptr;
}

bool ProductController::updateProductStock(const User &currentUser, const std::string &productId)
{
    if (currentUser.getUsertype() != "Seller")
    {
        std::cout << "只有商家才能修改商品库存。\n";
        return false;
    }
    Product *product = findProductById(productId);
    if (!product)
    {
        std::cout << "未找到ID为 '" << productId << "' 的商品。\n";
        return false;
    }

    int newQuantity;
    std::cout << "当前商品 '" << product->getName() << "' 库存: " << product->getQuantity() << std::endl;
    std::cout << "请输入新的库存量: ";
    while (!(std::cin >> newQuantity) || newQuantity < 0)
    {
        std::cout << "无效的库存量，请输入一个非负整数: ";
        clearInputBuffer();
    }
    clearInputBuffer();

    product->setTotalQuantity(newQuantity);
    saveProducts();
    std::cout << "商品 '" << product->getName() << "' 库存已更新为 " << newQuantity << "。\n";
    return true;
}

bool ProductController::updateProductPrice(const User &currentUser, const std::string &productId)
{
    if (currentUser.getUsertype() != "Seller")
    {
        std::cout << "只有商家才能修改商品价格。\n";
        return false;
    }
    Product *product = findProductById(productId);
    if (!product)
    {
        std::cout << "未找到ID为 '" << productId << "' 的商品。\n";
        return false;
    }

    double newPrice;
    std::cout << "当前商品 '" << product->getName() << "' 原价: " << product->getOriginalPrice() << std::endl;
    std::cout << "请输入新的原价: ";
    while (!(std::cin >> newPrice) || newPrice < 0)
    {
        std::cout << "无效的价格，请输入一个非负数: ";
        clearInputBuffer();
    }
    clearInputBuffer();

    product->setOriginalPrice(newPrice);
    saveProducts();
    std::cout << "商品 '" << product->getName() << "' 原价已更新为 " << newPrice << "。\n";
    return true;
}

bool ProductController::updateProductDescription(const User &currentUser, const std::string &productId)
{
    if (currentUser.getUsertype() != "Seller")
    {
        std::cout << "只有商家才能修改商品描述。\n";
        return false;
    }
    Product *product = findProductById(productId);
    if (!product)
    {
        std::cout << "未找到ID为 '" << productId << "' 的商品。\n";
        return false;
    }

    std::string newDescription;
    std::cout << "当前商品 '" << product->getName() << "' 描述: " << product->getDescription() << std::endl;
    std::cout << "请输入新的描述: ";
    std::getline(std::cin, newDescription); // Already cleared buffer if previous was numeric

    product->setDescription(newDescription);
    saveProducts();
    std::cout << "商品 '" << product->getName() << "' 描述已更新。\n";
    return true;
}

bool ProductController::updateProductName(const User &currentUser, const std::string &productId)
{
    if (currentUser.getUsertype() != "Seller")
    {
        std::cout << "只有商家才能修改商品名称。\n";
        return false;
    }
    Product *product = findProductById(productId);
    if (!product)
    {
        std::cout << "未找到ID为 '" << productId << "' 的商品。\n";
        return false;
    }

    std::string newName;
    std::cout << "当前商品名称: " << product->getName() << std::endl;
    std::cout << "请输入新的商品名称: ";
    std::getline(std::cin, newName);

    product->setName(newName);
    saveProducts();
    std::cout << "商品ID '" << productId << "' 名称已更新为 '" << newName << "'。\n";
    return true;
}

bool ProductController::applyDiscountToCategory(const User &currentUser, const std::string &category, double discountPercentage)
{
    if (currentUser.getUsertype() != "Seller")
    {
        std::cout << "只有商家才能应用分类折扣。\n";
        return false;
    }
    if (discountPercentage < 0 || discountPercentage > 100)
    {
        std::cout << "无效的折扣百分比。请输入0到100之间的值。\n";
        return false;
    }

    double discountRate = discountPercentage / 100.0;
    bool foundCategory = false;
    int updatedCount = 0;

    std::string targetCategory;
    if (category == "Book" || category == "图书")
        targetCategory = "Book";
    else if (category == "Clothing" || category == "Clothing")
        targetCategory = "Clothing";
    else if (category == "Food" || category == "Food")
        targetCategory = "Food";
    else
    {
        std::cout << "无效的商品分类: " << category << std::endl;
        return false;
    }

    for (auto &product_ptr : products)
    {
        if (product_ptr && product_ptr->getCategory() == targetCategory)
        {
            foundCategory = true;
            product_ptr->setDiscountRate(discountRate);
            updatedCount++;
        }
    }

    if (!foundCategory)
    {
        std::cout << "未找到分类为 '" << targetCategory << "' 的商品。\n";
        return false;
    }

    saveProducts();
    std::cout << "已对分类 '" << targetCategory << "' 中的 " << updatedCount << " 件商品应用了 " << discountPercentage << "% 的折扣。\n";
    return true;
}

json ProductController::handleGetMyProducts(int sellerId) const
{
    json response;
    json product_array = json::array();
    for (const auto &p : products)
    {
        if (p && p->getSellerId() == sellerId)
        {
            product_array.push_back(p->toJson());
        }
    }
    response["status"] = "SUCCESS";
    response["data"] = product_array;
    return response;
}

// void ProductController::manageProductsMenu(const User &currentUser)
// {
//     if (currentUser.getUsertype() != "Seller")
//     {
//         std::cout << "您没有权限管理商品。\n";
//         return;
//     }

//     int choice;
//     std::string productId_str, category_str;
//     double discount_val;

//     while (true)
//     {
//         std::cout << "\n--- 商品管理 (商家) ---\n";
//         std::cout << "1. 添加新商品\n";
//         std::cout << "2. 修改商品库存\n";
//         std::cout << "3. 修改商品价格\n";
//         std::cout << "4. 修改商品描述\n";
//         std::cout << "5. 修改商品名称\n";
//         std::cout << "6. 对分类应用折扣\n";
//         std::cout << "7. 查看所有商品 (详细信息)\n";
//         std::cout << "0. 返回上一级菜单\n";
//         std::cout << "请输入您的选择: ";

//         if (!(std::cin >> choice))
//         {
//             std::cout << "无效输入，请输入数字。\n";
//             clearInputBuffer();
//             continue;
//         }
//         clearInputBuffer(); // Important after reading a number

//         if (choice == 0)
//             break;

//         switch (choice)
//         {
//         case 1:
//             addProductInteractively(currentUser);
//             break;
//         case 2:
//             std::cout << "请输入要修改库存的商品ID: ";
//             std::getline(std::cin, productId_str);
//             updateProductStock(currentUser, productId_str);
//             break;
//         case 3:
//             std::cout << "请输入要修改价格的商品ID: ";
//             std::getline(std::cin, productId_str);
//             updateProductPrice(currentUser, productId_str);
//             break;
//         case 4:
//             std::cout << "请输入要修改描述的商品ID: ";
//             std::getline(std::cin, productId_str);
//             updateProductDescription(currentUser, productId_str);
//             break;
//         case 5:
//             std::cout << "请输入要修改名称的商品ID: ";
//             std::getline(std::cin, productId_str);
//             updateProductName(currentUser, productId_str);
//             break;
//         case 6:
//             std::cout << "请输入要应用折扣的商品分类 (Book, Clothing, Food): ";
//             std::getline(std::cin, category_str);
//             std::cout << "请输入折扣百分比 (例如, 输入10表示10%): ";
//             while (!(std::cin >> discount_val))
//             {
//                 std::cout << "无效输入，请输入数字: ";
//                 clearInputBuffer();
//             }
//             clearInputBuffer();
//             applyDiscountToCategory(currentUser, category_str, discount_val);
//             break;
//         case 7:
//             displayAllProducts(true); // Show detailed view for seller
//             break;
//         default:
//             std::cout << "无效的选择，请重试。\n";
//         }
//     }
// }

// void ProductController::viewAndSearchProductsMenu(const bool forSellerView, const int sellerID) const
// {
//     int choice;
//     std::string query;

//     while (true)
//     {
//         std::cout << "\n--- 浏览和搜索商品 ---\n";
//         std::cout << "1. 查看所有商品\n";
//         std::cout << "2. 按名称搜索商品\n";
//         std::cout << "3. 按分类查看商品\n";
//         std::cout << "0. 返回上一级菜单\n";
//         std::cout << "请输入您的选择: ";

//         if (!(std::cin >> choice))
//         {
//             std::cout << "无效输入，请输入数字。\n";
//             clearInputBuffer();
//             continue;
//         }
//         clearInputBuffer();

//         if (choice == 0)
//             break;

//         switch (choice)
//         {
//         case 1:
//             displayAllProducts(forSellerView, sellerID);
//             break;
//         case 2:
//         {
//             vector<Product *> searchResults;
//             std::cout << "请输入要搜索的商品名称关键字: ";
//             std::getline(std::cin, query);
//             searchResults = searchProductByName(query);
//             for (auto &product_ptr : searchResults)
//             {
//                 product_ptr->displayProductDetails(forSellerView); // 显示搜索结果
//             }
//         }
//         break;
//         case 3:
//             std::cout << "请输入要查看的商品分类 (Book, Clothing, Food): ";
//             std::getline(std::cin, query);
//             // Normalize common Chinese inputs to English categories if needed
//             if (query == "图书")
//                 query = "Book";
//             else if (query == "Clothing")
//                 query = "Clothing";
//             else if (query == "Food")
//                 query = "Food";
//             displayProductsByCategory(query);
//             break;
//         default:
//             std::cout << "无效的选择，请重试。\n";
//         }
//     }
// }

const std::vector<std::unique_ptr<Product>> &ProductController::getAllProducts() const
{
    return products;
}